/**
 * 家属管理页面JavaScript逻辑
 */

// 页面加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 检查登录状态
    if (!Auth.isLoggedIn()) {
        window.location.href = '../login.html';
        return;
    }

    // 检查用户角色
    if (!Auth.checkRole(UserRole.NORMAL_USER)) {
        UI.showMessage('您没有权限访问此页面', 'danger');
        setTimeout(() => {
            Auth.logout();
        }, 2000);
        return;
    }

    // 初始化页面
    init();
});

/**
 * 初始化页面
 */
async function init() {
    // 显示用户信息
    displayUserInfo();
    
    // 加载家属列表
    await loadFamilyList();
}

/**
 * 显示用户信息
 */
function displayUserInfo() {
    const userInfo = Auth.getUserInfo();
    if (userInfo) {
        const userName = userInfo.account || '用户';
        document.getElementById('userName').textContent = userName;
        
        // 设置头像首字母
        const avatar = document.getElementById('userAvatar');
        avatar.textContent = userName.charAt(0).toUpperCase();
    }
}

/**
 * 加载家属列表
 */
async function loadFamilyList() {
    try {
        const families = await HttpClient.get('/family/list');
        
        const tbody = document.getElementById('familyTableBody');
        tbody.innerHTML = '';
        
        if (!families || families.length === 0) {
            tbody.innerHTML = `
                <tr>
                    <td colspan="5" style="text-align: center; padding: 40px; color: #999;">
                        <i class="fas fa-users" style="font-size: 48px; margin-bottom: 10px; display: block;"></i>
                        暂无家属信息，点击"添加家属"按钮添加
                    </td>
                </tr>
            `;
            return;
        }
        
        families.forEach(family => {
            const row = document.createElement('tr');
            row.innerHTML = `
                <td>${family.name || '-'}</td>
                <td>${family.age || '-'}</td>
                <td>${family.idNum || '-'}</td>
                <td>${family.relationshipDesc || '-'}</td>
                <td>
                    <button class="btn btn-danger btn-sm" onclick="handleDeleteFamily(${family.familyId}, '${family.name}')">
                        <i class="fas fa-trash"></i> 删除
                    </button>
                </td>
            `;
            tbody.appendChild(row);
        });
    } catch (error) {
        console.error('加载家属列表失败:', error);
        UI.showMessage('加载家属列表失败', 'danger');
    }
}

/**
 * 显示添加家属模态框
 */
function showAddFamilyModal() {
    document.getElementById('addFamilyModal').classList.add('show');
    // 清空表单
    document.getElementById('addFamilyForm').reset();
}

/**
 * 关闭添加家属模态框
 */
function closeAddFamilyModal() {
    document.getElementById('addFamilyModal').classList.remove('show');
}

/**
 * 处理添加家属
 */
async function handleAddFamily() {
    const name = document.getElementById('familyName').value.trim();
    const age = document.getElementById('familyAge').value;
    const relation = document.getElementById('familyRelation').value;
    const idNum = document.getElementById('familyIdNum').value.trim();
    
    // 表单验证
    if (!name) {
        UI.showMessage('请输入家属姓名', 'warning');
        return;
    }
    
    if (!age || age < 0 || age > 150) {
        UI.showMessage('请输入有效的年龄', 'warning');
        return;
    }
    
    if (!relation) {
        UI.showMessage('请选择关系', 'warning');
        return;
    }
    
    if (!idNum) {
        UI.showMessage('请输入身份证号', 'warning');
        return;
    }
    
    // 验证身份证号格式
    if (!validateIdCard(idNum)) {
        UI.showMessage('身份证号格式不正确', 'warning');
        return;
    }
    
    try {
        const data = {
            name: name,
            age: parseInt(age),
            relationship: parseInt(relation),
            idNum: idNum
        };

        await HttpClient.post('/family', data);
        
        UI.showMessage('添加家属成功', 'success');
        closeAddFamilyModal();
        
        // 重新加载家属列表
        await loadFamilyList();
    } catch (error) {
        console.error('添加家属失败:', error);
        UI.showMessage(error.message || '添加家属失败', 'danger');
    }
}

/**
 * 处理删除家属
 */
async function handleDeleteFamily(familyId, familyName) {
    UI.confirm(`确定要删除家属"${familyName}"吗？`, async () => {
        try {
            await HttpClient.delete(`/family/${familyId}`);
            
            UI.showMessage('删除家属成功', 'success');
            
            // 重新加载家属列表
            await loadFamilyList();
        } catch (error) {
            console.error('删除家属失败:', error);
            UI.showMessage(error.message || '删除家属失败', 'danger');
        }
    });
}

/**
 * 验证身份证号格式
 */
function validateIdCard(idCard) {
    // 15位或18位身份证号正则表达式
    const pattern = /^\d{18}$/;
    return pattern.test(idCard);
}

/**
 * 退出登录
 */
function handleLogout() {
    UI.confirm('确定要退出登录吗？', () => {
        Auth.logout();
    });
}

